class SessionsController < ApplicationController
  def destroy
	session[:user_id] = nil
    cookies.delete :userapp_login_pass
    cookies.delete :userapp_login
    redirect_to login_path
  end
  
  #render the signin page
  def new
  end
  
  def create
    session[:user_id] = nil #clear the session for id
    if request.post?
      @user = User.authenticate(params[:name], params[:password])
      if @user
        session[:user_id] = @user.id
        remember_login @user, params[:remember]
        uri = session[:original_uri]
        session[:original_uri] = nil
        redirect_to novels_path
      else
	    render :action => "new" 
        flash[:error] = "login failed."
      end
    end
  end
  
  def remember_login(user, remember=true) #by cookies
	
    if remember
	  cookie_pass = [Array.new(9){rand(256).chr}.join].pack("m").chomp
      cookies[:userapp_login_pass] = { :value => cookie_pass, :expires => 30.days.from_now }
      cookies[:userapp_login] = { :value => user.name, :expires => 30.days.from_now }
      cookies_hash = Digest::MD5.hexdigest(cookie_pass + user.hashed_password)
      user.cookies_hash=cookies_hash
	  user.fake_password
      user.save!
    else
      cookies.delete :userapp_login_pass
      cookies.delete :userapp_login
    end
  end
end
